#!/usr/bin/perl
#marruda@uolinc.com - 20/05/2005

use strict;
use Sys::Hostname;
use Socket;
use Sys::Syslog;

#my $hostname = shift;
#$hostname = hostname if (not $hostname);

my $hostname = "localhost";

my $server="/server-status";
my $port = "80";
my $inf="?auto";
my %board;
my $count;
my %status;
my @topipe;


my $check = `ps -ef |grep getwebstatus.pl |grep -v grep|wc -l|xargs`;
chomp $check;
if ($check ge "4") #evita um novo processo caso haja algum rodando 
{
        print "Alread running - $check\n";
        exit 0;
}

#possibilidades no scoreboard
$status{'W'} = "SendingReply";
$status{'_'} = "WaitingforConnection";
$status{'S'} = "StartingUp";
$status{'R'} = "ReadingRequest";
$status{'K'} = "Keepalive";
$status{'D'} = "DNSLookup";
$status{'C'} = "ClosingConnection";
$status{'L'} = "Logging";
$status{'G'} = "GracefullyFinishing";
$status{'I'} = "IdleCleanupOfWorker";
$status{'.'} = "OpenSlotWithNoCurrentProcess";

#conexao ao server-status
my $iaddr= inet_aton($hostname) or die "Error: $!";
my $paddr=sockaddr_in($port, $iaddr) or die "Error: $!";
my $proto=getprotobyname('tcp') or die "Error - Protocol: $!";
socket(SOCK1, PF_INET, SOCK_STREAM, $proto) or die "Error: $!"; 
connect(SOCK1, $paddr) or die "Error: $!";
my $msg = "GET /$server$inf\n";
send(SOCK1, $msg, 0);
my @out = <SOCK1>;
close(SOCK1) or die "close: $!";
chomp @out;

#tratar scoreboard e adicionar na matriz score
$out[$#out] =~ s/Scoreboard\: //;
chop($out[$#out]);
my @score=split(//,$out[$#out]);

#adicionar no hash scoreboard
foreach (@score)
{
	$board{$status{$_}}++;
}

$#out=$#out-1;

#relacionar letras com nomes e adicionar na matriz out
foreach (keys (%board))
{
	push (@out, "$_ $board{$_}");
}

#tratar saida e gravar em uma nova matriz que sera gravada no pipe
foreach (@out)
{
	$_ =~ s/Workers/WP/g;
	$_ =~ s/Servers/WP/g;
	$_ =~ s/://g;
	$_ =~ s/\.//g if (not $_ =~ /\w\./);
	$_ =~ s/(\w)\s(\D)/$1$2/g;
	push (@topipe, $_);
	print "$_ ";
}

#gravar no pipe
openlog("webserver", 'ndelay', 'user');
syslog("info", "@topipe");
closelog();
